import React, { useEffect, useRef, useState } from 'react'
import Footer from '../component/Footer'
import axios from 'axios';
import { sleep } from 'antd-mobile/es/utils/sleep'
import { Space, Divider, Typography, Swiper, Overlay, ActionSheet } from 'react-vant'
import Share from '../component/Share';
import '../css/douyin.css'
import 'animate.css'
const initialState = { progress: 0, playing: false };

export default function Douyin() {

    const [value, setValue] = useState(1)
    const [tabList, setTabList] = useState([
        { name: '关注' }, { name: '推荐' }, { name: '附近' }
    ])
    let setTab = (index) => {
        console.log(index);
        setValue(index)
    }
    // 获取视频元素的ref引用
    const videoRef = useRef();
    const videoRefList = useRef([])
    function getRef(dom) {
        if (!(dom instanceof HTMLElement) && dom !== null) {
            console.error('Invalid input: dom must be a DOM element or null.');
            return null; // 提供明确的返回值
        }
        // 对 null 的处理，显式返回 null
        if (dom === null) {
            return null;
        }
        // 异常处理：确保 videoRefList.current 是数组且存在 push 方法
        if (typeof videoRefList !== 'object' || videoRefList === null || !Array.isArray(videoRefList.current)) {
            console.error('Invalid videoRefList.current: Must be an array.');
            return null;
        }
        try {
            // 限制数组大小的逻辑
            if (videoRefList.current.includes(dom)) { //如果存在
                return videoRefList.current; // 返回当前列表，不进行任何更改
            }
            if (videoRefList.current.length >= data.length) {
                videoRefList.current.shift(); // 移除最旧的元素
            }
            videoRefList.current.push(dom);
        } catch (error) {
            console.error('Error pushing dom to videoRefList:', error);
            return null; // 在异常情况下提供返回值
        }
    }
    const [videoHeight, setVideoHeight] = useState(0)
    const palseRef = useRef()
    //视频播放
    //单机控制视频暂停播放
    let VideoClick = (e) => {
        if (e.changedTouches[0].pageX !== x) return
        try {
            if (e.target.paused) { //如果暂停
                e.target.play(); //播放
                palseRef.current.style.display = 'none';
            } else {
                e.target.pause(); //暂停
                palseRef.current.style.display = 'block';
            }
        } catch (error) {
            console.error("Error playing/pausing the video:", error);
        }
    }
    //触摸位置
    // 进度条快进或者后退
    const [x, setX] = useState(0)
    const [y, setY] = useState(0)
    let getPageX = (e) => {
        // console.log(e.changedTouches);
        setX(e.touches[0].pageX)
        setY(e.touches[0].pageY)
    }
    let videoGo = (e) => {
        if (e.changedTouches && e.changedTouches.length > 0) {
            const currentVideo = e.target;
            const currentTime = currentVideo.currentTime;
            const totalDuration = currentVideo.duration;

            if (currentTime / totalDuration >= 0.5) { // 当播放到达70%时
                preloadNextVideos(swiperRef.current.activeIndex);
            }
            var videoTime = e.target.duration //总时长
            var windowWidth = window.innerWidth  //屏幕宽度
            // 验证videoDuration和screenWidth以避免NaN计算
            if (videoTime > 0 && windowWidth > 0) {
                var palseWith = (videoTime / windowWidth) * 3//进度条要走的长度
                if (e.changedTouches[0].pageX > x) {
                    //如果changedTouches[0].pageX大于x，说明是向右滑动
                    e.target.currentTime += palseWith * 0.5
                } else e.target.currentTime -= palseWith * 0.5
            }
        }
    }
    //进度条
    const progress = useRef()
    const bar = useRef()
    let timeUp = (e) => {

        var videoTime = e.target.duration //总时长
        // 检查videoTime确保不为0，避免除以0导致NaN的情况
        if (videoTime === 0) {
            console.error('Video duration is 0.');
            return;
        }
        var currTime = e.target.currentTime //当前播放时间
        var pre = currTime / videoTime //进度条比例
        // console.log(pre);
        var windowWidth = window.innerWidth  //屏幕宽度
        var palseWith = windowWidth * pre //进度条要走的长度
        var progressWidth = progress.current.offsetWidth //进度条已经走得长度
        if (progress.current && bar.current) {
            if (palseWith > windowWidth) {
                progress.current.style.left = windowWidth + 'px'; // 重置进度条
                bar.current.style.width = windowWidth + 'px';
            } else {
                // 优化DOM操作，减少不必要的样式设置
                bar.current.style.width = palseWith + 'px';
                bar.current.style.background = '#888';
                progress.current.style.left = palseWith + 'px';
            }
        }
    }
    // 触底加载
    const [data, setData] = useState([])
    const [hasMore, setHasMore] = useState(true)
    const [page, setPage] = useState(1)
    // 向后端获取视频
    let getData = async () => {
        const { data: { videos } } = await axios.get('http://localhost:3000/video', { params: { page: 1 } })
        setData(videos)
        setPage(val => val + 1)

    }
    const swiperRef = useRef()
    // swipre切换
    let swipreChange = async () => {
        if (swiperRef.current.activeIndex === -1) {
            return
        }
        //刷到最后一条视频时再去向后端请求新的数据
        if (swiperRef.current.activeIndex == videoRefList.current.length - 1) {
            const append = await axios.get('http://127.0.0.1:3000/video', { params: { page: page } }).then(res => {
                return res.data.videos
            })
            setData(val => [...val, ...append])
            setHasMore(append.length > 0)
            setPage(val => val + 1)
            await sleep(200)
        }

        palseRef.current.style.display = 'none'//隐藏暂停按钮
        for (let i = 0; i < videoRefList.current.length; i++) {
            videoRefList.current[i].pause() //暂停其他视频
            videoRefList.current[i].currentTime = 0 //重置其他视频的播放时间
        }
        try {
            let time = setTimeout(() => {
                // 播放当前视频
                videoRefList.current[swiperRef.current.activeIndex].play()
            }, 500)
            return () => clearTimeout(time)
        } catch (e) {
            console.log(e)
        }
    }
    const [shareShow, setShareShow] = useState(false)
    let closeShare = (flag) => {
        setShareShow(flag)
    }

    useEffect(() => {
        return () => {
            getData()
        }
    }, [])
    // 评论区
    const [visible, setVisible] = useState(false)
    const onCancel = () => setVisible(false)
    // 点赞
    let iLike = (e) => {
        if (e.target.src === "http://localhost:3001/imgs/%E5%9B%BE%E6%A0%87%20ACxSujW@1x.png") {
            e.target.src = "http://localhost:3001/imgs/图标 ACxSujW@1x (1).png"
        } else {
            e.target.src = "http://localhost:3001/imgs/%E5%9B%BE%E6%A0%87%20ACxSujW@1x.png"
        }
    }
    let preloadVideoElements = []; // 存储预加载用的 <video> 元素

    function handleTimeUpdate(event) {

    }
    const MAX_PRELOAD_COUNT = 2;
    function preloadNextVideos(currentIndex) {
        // 清理不再需要的已预加载视频资源
        for (let i = 0; i < preloadVideoElements.length; i++) {
            const preloadVideo = preloadVideoElements[i];
            const preloadIndex = preloadVideo.dataset.index;
            if (preloadIndex <= currentIndex) {
                preloadVideo.src = ""; // 清空源，释放资源
                preloadVideo.remove();
                preloadVideoElements.splice(i, 1);
                i--; // 由于数组长度减小，需要回退一位继续检查
            }
        }

        // 预加载下两条视频
        for (let i = 1; i <= MAX_PRELOAD_COUNT; i++) {
            const nextIndex = currentIndex + i;
            if (nextIndex >= data.length) break; // 避免超出视频列表范围

            const nextVideoUrl = data[nextIndex].VideoSrc; //data是包含所有视频信息的数组

            const preloadVideo = document.createElement("video");
            preloadVideo.preload = "auto";
            preloadVideo.src = nextVideoUrl;
            preloadVideo.style.display = "none"; // 隐藏预加载的视频元素
            preloadVideo.dataset.index = nextIndex; // 保存预加载视频的索引
            document.body.appendChild(preloadVideo); // 将预加载元素添加到 DOM 中

            preloadVideo.addEventListener("canplaythrough", () => {
                console.log(`Video at index ${nextIndex} has been preloaded.`);
            });

            preloadVideoElements.push(preloadVideo);
        }
    }
    return (
        <div id='dy' >
            <div className='demo-flex'>
                <div className='demo-item'>
                    <div>
                        <img src={process.env.PUBLIC_URL + '/imgs/antOutline-camera dbthJ2R@1x.png'} style={{ marginLeft: '15px', zIndex: 5 }} alt='' />
                    </div>
                    <div>
                        <Space align="center" divider={<Divider type="vertical" />}>
                            {
                                tabList.map((item, index) =>
                                    <Typography.Link className={value === index ? 'tabactive' : ''} onClick={() => { setTab(index) }} id='tab' key={index}>
                                        {item.name}
                                    </Typography.Link>
                                )
                            }
                        </Space>
                    </div>
                    <div>
                        <img src={process.env.PUBLIC_URL + '/imgs/mb-search lhAUTys@1x.png'} style={{ marginRight: '15px', zIndex: 5 }} alt='' />
                    </div>
                </div>
            </div>
            <Swiper
                vertical
                touchable
                onChange={(e) => { swipreChange(e) }}
                style={{ height: '100%', width: '100%' }}
                ref={swiperRef}
                initialSwipe={-1}
                indicator={() => { }}
                id='swiperr'
                loop={false}
            >
                {
                    data.map((item, index) =>
                        <Swiper.Item key={item._id}>
                            <video
                                id={`id${index}`}
                                key={item._id}
                                loop
                                playsInline
                                x5-playsinline="true"
                                onTimeUpdate={(e) => { timeUp(e) }}
                                disablePictureInPicture
                                x5-video-player-type="h5"
                                width='100%'
                                height='95%'
                                onLoadedData={(e) => {
                                    videoRefList.current[0].play()
                                    if (e.target.videoHeight > 720) e.target.className = 'playFit'
                                }}
                                // className='playFit'
                                ref={getRef}
                                onTouchStart={(e) => { getPageX(e) }}
                                onTouchMove={(e) => { videoGo(e) }}
                                onTouchEnd={VideoClick}
                                muted={true}
                            >
                                <source src={item.VideoSrc} type='video/mp4' />
                            </video>
                            {/* 头像 */}
                            <div className='headerBox'>
                                <img src={process.env.PUBLIC_URL + "/img/3.png"} alt="" className='header' />
                            </div>

                            {/* 视频标题 */}
                            <div className='videoTitle'>{item.title}</div>
                            {/* 用户名称 */}
                            <div className='VideoUser'>@祝英台大战哥斯拉</div>
                            {/* 音乐名 */}
                            <div className='warp'>
                                <div className='VideoMusicName'>特斯河之赞-九宝乐队</div>
                            </div>
                            {/* 左下角音乐图标 */}
                            <img
                                className='musicDisk'
                                alt=''
                                src={process.env.PUBLIC_URL + '/imgs/svg-music-disk Copy LlLsFBl@1x.png'}
                            />
                            {/* 右下角音乐图标 */}
                            <img
                                className='music'
                                alt=''
                                src={process.env.PUBLIC_URL + '/imgs/群组 Copy 2 9VFHgZB@1x.png'}
                            />
                            <img
                                className='flotMusic1'
                                alt=''
                                src={process.env.PUBLIC_URL + '/imgs/svg-music-note Copy ojVDt0J@1x.png'}
                            />
                            <img
                                className='flotMusic2'
                                alt=''
                                src={process.env.PUBLIC_URL + '/imgs/svg-music-notes Copy UBRfRsy@1x.png'}
                            />

                            {/* 转发图片 */}
                            <div className='shareBox'>
                                <img
                                    src={process.env.PUBLIC_URL + '/imgs/fas fa-share CgMPcCL@1x.png'}
                                    alt=''
                                    onClick={() => { setShareShow(true) }}
                                />
                            </div>
                            {/* 评论图标 */}
                            <div className='commitBox' onClick={() => setVisible(true)}>
                                <img
                                    src={process.env.PUBLIC_URL + '/imgs/图标 95pxlS8@1x.png'}
                                    alt=''
                                    className='commit'

                                />
                                <p style={{ width: '100%', fontSize: '0.5rem' }}>暂无评论</p>
                            </div>

                            {/* 点赞图标 */}
                            <div className='likeBox'>
                                <img
                                    src={process.env.PUBLIC_URL + '/imgs/图标 ACxSujW@1x.png'}
                                    alt=''
                                    className='like'
                                    onClick={(e) => { iLike(e) }}
                                />
                                <p style={{ width: '100%', fontSize: '0.5rem' }}>8.8W</p>
                            </div>



                        </Swiper.Item>
                    )
                }

            </Swiper >
            <img
                ref={palseRef}
                id="videoPalse"
                src='../暂停.png'
                alt=""
            />
            {/* 进度条 */}
            <div id='ProgressBar' >
                <div ref={bar} style={{ height: '2px', position: 'absolute' }}></div>
                <div id='Progress' ref={progress}></div>
            </div>
            {/* 分享 */}
            <Overlay visible={shareShow} onClick={() => setShareShow(false)} >
                <div className={shareShow ? 'share' : 'share_show share'}>
                    <Share onClose={closeShare} />
                </div>
            </Overlay>
            {/* 评论 */}
            <ActionSheet visible={visible} onCancel={onCancel} duration={2} >
                <div style={{ padding: '16px 16px 160px' }} className='Comment'>
                    <img
                        src={process.env.PUBLIC_URL + '/imgs/fas fa-times M7jRAhK@1x.png'}
                        className='close'
                        alt=''
                        onClick={onCancel}
                    />
                    <p>评论详细</p>
                    <div>
                        <div style={{ width: '100%', fontSize: '0.8rem', lineHeight: '200px', textAlign: 'center', color: '#fff' }}>暂无评论,快来发表第一条评论吧！</div>
                    </div>
                </div>
            </ActionSheet>
            <Footer></Footer>
        </div>
    )
}


